package com.xinz.serialization;

import java.util.ArrayList;
import java.util.HashMap;

public class IndexMap<K, V> {

	HashMap<K, Integer> map = new HashMap<K, Integer>();
	ArrayList<V> list = new ArrayList<V>();
	
	/**
	 * 
	 * @param k
	 * @param v
	 * @return
	 * 		如果已经存在值 则抛出IllegalStateException;
	 */
	public int put(K k,V v) {
		int index = list.size();
		list.add(v);
		if(map.put(k, index) != null) {
			throw new IllegalStateException();
		}
		return index;
	}
	
	public V get(K key) {
		Integer index = map.get(key);
		if(index == null) {
			throw new IndexOutOfBoundsException(key.toString());
		}
		return list.get(index);
	}
	
	public Integer indexOfKey(K key) {
		Integer index = map.get(key);
		if(index == null) {
			return -1;
		}
		return index;
	}

	public V valueAt(int index) {
		return list.get(index);
	}
}
